package cn.gailvlun.gll.presentation.chat;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewEditorActionEvent;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.net.base.friend.FriendNotification;
import cn.gailvlun.gll.presentation.base.App;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.config.Constants;
import cn.gailvlun.gll.databinding.ActivityAddFriendBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.base.friend.AddFriendReq;
import cn.gailvlun.gll.presentation.chat.adapter.AddFriendAdapter;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;



public class AddFriendActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, AddFriendActivity.class);
        context.startActivity(intent);
    }

    private ActivityAddFriendBinding mBinding;
    private AddFriendAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_friend);

        mAdapter = new AddFriendAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.srl.setOnRefreshListener(this);
        mBinding.srl.setOnLoadmoreListener(this);
        mBinding.srl.setEnableLoadmore(false);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });

        Observable<CharSequence> obEditor = RxTextView.editorActionEvents(mBinding.cetSearch).map(new Function<TextViewEditorActionEvent, CharSequence>() {
            @Override
            public CharSequence apply(TextViewEditorActionEvent textViewEditorActionEvent) throws Exception {
                return mBinding.cetSearch.getText();
            }
        });
        Observable<CharSequence> obInput = RxTextView.textChanges(mBinding.cetSearch);

        Observable.merge(obEditor, obInput)
                .debounce(Constants.Search.debounce, TimeUnit.MILLISECONDS)
                .skip(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        loadByContent(charSequence.toString());
                    }
                });
    }

    private void loadByContent(String content) {
        if (!IsEmpty.string(content)) {
            HttpMethods.getProfileService()
                    .getProfileByKeyword(content)
                    .compose(RxUtil.<ListRes<Profile>>applyScheduler())
                    .subscribe(new HttpSubscriber<ListRes<Profile>>() {
                        @Override
                        protected void onSuccess(ListRes<Profile> response) {
                            loadRecyclerView(response.getResults(), true, response.isNext());
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable ListRes<Profile> response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        } else {
            loadRecyclerView(null, true, false);
        }
    }

    private void loadRecyclerView(List<Profile> list, boolean isRefresh, boolean isMore) {
        if (isRefresh) {
            mAdapter.clear();
            if (IsEmpty.list(list)) {

            } else {
                mAdapter.addAll(list);
            }
            mBinding.srl.finishRefresh();
        } else {
            mAdapter.addAll(list);
        }

        mBinding.srl.setEnableLoadmore(isMore);
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {

    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        loadByContent(mBinding.cetSearch.getText().toString());
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onAddFriend(Profile item) {
            HttpMethods.getFriendService()
                    .addFriend(new AddFriendReq(item.getId()))
                    .compose(RxUtil.<FriendNotification>applyScheduler())
                    .subscribe(new HttpSubscriber<FriendNotification>() {
                        @Override
                        protected void onSuccess(FriendNotification response) {
                            ToastUtil.showShort("请求成功");
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable FriendNotification response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }
    }

    public static class Util {
        public static boolean getBtnEnable(Profile profile) {
            if (profile.getIs_friend()) {
                return false;
            } else {
                return true;
            }
        }

        public static Drawable getBtnBg(Profile profile) {
            if (profile.getIs_friend()) {
                return ContextCompat.getDrawable(App.getInstance(), R.drawable.rounded_b44);
            } else {
                return ContextCompat.getDrawable(App.getInstance(), R.drawable.rounded_apricot);
            }
        }

        public static String getBtnText(Profile profile) {
            if (profile.getIs_friend()) {
                return "已添加";
            } else {
                return "加好友";
            }
        }
    }
}
